package controllers;

import play.*;
import play.data.validation.*;
import play.db.jpa.JPA;
import play.mvc.*;

import java.util.*;

import javax.persistence.Query;

import models.*;

public class Application extends Controller {

    public static void index() {
    	 List<Restaurant> restaurantList = Restaurant.findAll();
    	 
    	 // get all restaurants that are close to search string
    	 
    	 
    	 // get all favorite restaurants for logged-in user
    	 List<Restaurant> favoriteList = new LinkedList<Restaurant>();
    	 if(session.contains("username") && session.get("username") != null ) {
    		 String userEmail = session.get("username");
    		 favoriteList = Favorite.find("SELECT r FROM Restaurant r WHERE r IN (SELECT f.restaurant FROM Favorite f WHERE f.customer.person.email = ?)", userEmail).fetch();
    	 }
    	 
    	 render(restaurantList, favoriteList);
    }

	public static void impress() {
		render();
	}
	
	public static void contact() {
		render();
	}
	
	public static void about() {
		render();
	}
	
	public static void help() {
		render();
	}
	
	public static void restaurantdetail(Long restid) {
		Restaurant resta = Restaurant.findById(restid);
		List<Meal> meals = Meal.find("byRestaurant", resta).fetch();
		//TO DO MEALS
		render(resta, meals);
	} 
	
	public static void searchRestaurantByZip(@Required String zip)
	{
		List<Restaurant> found = new LinkedList<Restaurant>();
		found = Restaurant.find("SELECT r FROM Restaurant r WHERE r.address.zip=?", zip).fetch();
		renderJSON(found);
	}

	public static void searchRestaurantByFood(@Required String food)
	{
		List<Restaurant> found = new LinkedList<Restaurant>();
		String foodQ = String.format("SELECT r FROM Restaurant r WHERE EXISTS " +
			"(SELECT m FROM Meal m "
			+"WHERE m.restaurant=r "
			+"AND (lower(m.title) LIKE '%s' "
				+"OR lower(m.description) LIKE '%s'))", 
				"%" + food.toLowerCase() + "%", 
				"%" + food.toLowerCase() + "%");

		found = Restaurant.find(foodQ).fetch();
		renderJSON(found);
	}
}